from django.core.management.base import BaseCommand, CommandError
from svp.warper.models import PlanetRequest
from subprocess import call
from time import sleep

class Command(BaseCommand):
  
  def handle(self, *args, **options):
    while True:
      try:
        # Check if there are any outstanding panoramas.
        pending = PlanetRequest.objects.filter(waiting=True)

        if bool(pending):
          # There is at least one pending request.
          # Select the oldest pending request.
          request = pending[0]
          # Set the request to be no longer waiting.
          request.waiting = False
          request.save()

          outfile = ('/home/jack/src/street-view-planets/planet/%d.jpg' %
              request.id)
          args = ['/home/jack/src/street-view-planets/cpp/planet', '-pano',
              request.panorama, '-outfile', outfile, '-width', '768', '-height',
              '768']
          result = call(args)

          # Set the request to be completed.
          request.complete = True
          request.save()
          print "Warping completed"
        else:
          # There are no pending requests.
          print "No jobs pending"
          sleep(0.5)
      except Exception as ex:
        print ex
        sleep(0.5)

